/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * jdOperacionesEmpresa.java
 *
 * Created on 02-sep-2010, 10:57:50
 */

package gestionseguridadadministrativacliente;

import administracion.delegate.GestionPedidosDelegate;
import administracion.helper.MiTablePrint;
import administracion.helper.Utiles_MensajesDialogo;
import administracion.helper.Utiles_Tabla;
import com.jidesoft.hints.ListDataIntelliHints;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdesktop.beansbinding.AutoBinding;
import org.jdesktop.beansbinding.BindingGroup;
import org.jdesktop.beansbinding.ELProperty;
import org.jdesktop.swingbinding.JTableBinding;
import org.jdesktop.swingbinding.SwingBindings;
import suministros.ejb30.TO.EmpresaTO;

/**
 *
 * @author Luis_Angel
 */
public class jdOperacionesEmpresa extends javax.swing.JDialog {

    /** Creates new form jdOperacionesEmpresa */
     private ListDataIntelliHints intelliHintsEmpresa;
     private List<EmpresaTO> empresas;
     private List<EmpresaTO> empresas_temp;
     private JTableBinding jTableBinding;
     private BindingGroup bindingGroup;
     private boolean isEdicion;
     
    public jdOperacionesEmpresa(java.awt.Frame parent, boolean modal, boolean isEdicion) {
        super(parent, modal);
        initComponents();
        empresas_temp = new ArrayList(1);
        this.isEdicion = isEdicion;
        try {
            empresas = GestionPedidosDelegate.getInstance().obtenerEmpresas();
            this.actualizaTablaEmpresas(empresas);
            this.cargaHintsIndependientes();
        } catch (Exception ex) {
            Logger.getLogger(jdOperacionesEmpresa.class.getName()).log(Level.SEVERE, null, ex);
        }
        habilitaComandos();
    }

    private void habilitaComandos(){
        this.jbEditar.setVisible(isEdicion);
        if(isEdicion)
            this.setTitle("Modificar Empresas");
        else
            this.setTitle("Consultar Empresas");
    }

    private void cargaHintsIndependientes() throws Exception {
         this.intelliHintsEmpresa = new ListDataIntelliHints(this.jtfEmpresa,empresas);
    }

     private EmpresaTO getEmpresacodigo(String dni){
         EmpresaTO retorno = null;
        for (EmpresaTO empresa : this.empresas) {
          if (empresa.getRuc().equalsIgnoreCase(dni)) {
            retorno = empresa;
            break;
          }
        }
        return retorno;
    }

    private void buscarEmpresa()
      {
        EmpresaTO emp;
        if (this.jtfRuc.getText().trim().length() < 1) {
          try { emp = (EmpresaTO)this.intelliHintsEmpresa.getSelectedHint();
          } catch (NullPointerException ex) {
            emp = null;
          }
        } else {
          emp = this.getEmpresacodigo(this.jtfRuc.getText().trim());
        }
        if (emp == null) {
          Utiles_MensajesDialogo.mensajeError("La empresa no existe!");
          this.jtfRuc.setText("");
          emp = null;
        } else {
          this.jtfEmpresa.setText(emp.getRazon()+ " - " + emp.getRuc());
          this.jtfRuc.setText(emp.getRuc());
          this.empresas_temp.clear();
          this.empresas_temp.add(emp);
          this.actualizaTablaEmpresas(this.empresas_temp);
       //   this.ruc_proveedor=pro.getCodProveedor();
            try {
           //     this.detalles_solicitud = GestionPedidosDelegate.getInstance().getDetallesSolicitud(pro.getCodProveedor(), this.nro_solicitud);
           //     actualizaTablaDetallesSolicitud();
            } catch (Exception ex) {
                Logger.getLogger(jdVerUsuarios.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

    }

      private void actualizaTablaEmpresas(List<EmpresaTO> empresas_find) {
            this.bindingGroup = new BindingGroup();
            this.jTableBinding = SwingBindings.createJTableBinding(AutoBinding.UpdateStrategy.READ, empresas_find, this.jtEmpresas);

            JTableBinding.ColumnBinding columnBinding0 = this.jTableBinding.addColumnBinding(ELProperty.create("${ruc}"));

            columnBinding0.setColumnName("RUC");
            columnBinding0.setColumnClass(String.class);
            columnBinding0.setEditable(false);

            JTableBinding.ColumnBinding columnBinding1= this.jTableBinding.addColumnBinding(ELProperty.create("${razon}"));

            columnBinding1.setColumnName("RAZON SOCIAL");
            columnBinding1.setColumnClass(String.class);
            columnBinding1.setEditable(false);


            JTableBinding.ColumnBinding columnBinding2 = this.jTableBinding.addColumnBinding(ELProperty.create("${descripcion}"));

            columnBinding2.setColumnName("DIRECCION");
            columnBinding2.setColumnClass(String.class);
            columnBinding2.setEditable(false);

            JTableBinding.ColumnBinding columnBinding3 = this.jTableBinding.addColumnBinding(ELProperty.create("${principal}"));

            columnBinding3.setColumnName("Principal");
            columnBinding3.setColumnClass(Boolean.class);
            columnBinding3.setEditable(false);

            this.bindingGroup.addBinding(this.jTableBinding);
            this.bindingGroup.bind();
            int[] porcentajes= {10,40,40,10};
            try {
                Utiles_Tabla.definirAnchoColumnasJTable(this.jtEmpresas, porcentajes);
            } catch (Exception ex) {
                Logger.getLogger(jdOperacionesEmpresa.class.getName()).log(Level.SEVERE, null, ex);
            }

        }



    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jtEmpresas = new javax.swing.JTable();
        jtfEmpresa = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jtfRuc = new javax.swing.JTextField();
        jLabel18 = new javax.swing.JLabel();
        jbCancelar = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jbEditar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jtEmpresas.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "RUC", "RAZON SOCIAL", "DIRECCION"
            }
        ));
        jtEmpresas.setName("jtEmpresas"); // NOI18N
        jScrollPane1.setViewportView(jtEmpresas);

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(gestionseguridadadministrativacliente.GestionSeguridadAdministrativaclienteApp.class).getContext().getResourceMap(jdOperacionesEmpresa.class);
        jtfEmpresa.setFont(resourceMap.getFont("jtfEmpresa.font")); // NOI18N
        jtfEmpresa.setName("jtfEmpresa"); // NOI18N
        jtfEmpresa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtfEmpresaActionPerformed(evt);
            }
        });
        jtfEmpresa.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jtfEmpresaKeyPressed(evt);
            }
        });

        jLabel7.setFont(resourceMap.getFont("jLabel7.font")); // NOI18N
        jLabel7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconoscomb/16x16ozygen/apps/klatin.png"))); // NOI18N
        jLabel7.setText(resourceMap.getString("jLabel7.text")); // NOI18N
        jLabel7.setName("jLabel7"); // NOI18N

        jtfRuc.setName("jtfRuc"); // NOI18N
        jtfRuc.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtfRucActionPerformed(evt);
            }
        });
        jtfRuc.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jtfRucKeyPressed(evt);
            }
        });

        jLabel18.setFont(resourceMap.getFont("jLabel18.font")); // NOI18N
        jLabel18.setText(resourceMap.getString("jLabel18.text")); // NOI18N
        jLabel18.setName("jLabel18"); // NOI18N

        jbCancelar.setFont(resourceMap.getFont("jbCancelar.font")); // NOI18N
        jbCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconoscomb/16x16ozygen/actions/button_cancel.png"))); // NOI18N
        jbCancelar.setMnemonic('C');
        jbCancelar.setText(resourceMap.getString("jbCancelar.text")); // NOI18N
        jbCancelar.setName("jbCancelar"); // NOI18N
        jbCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbCancelarActionPerformed(evt);
            }
        });

        jButton1.setFont(resourceMap.getFont("jButton1.font")); // NOI18N
        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jbEditar.setFont(resourceMap.getFont("jbEditar.font")); // NOI18N
        jbEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconoscomb/16x16ozygen/actions/button_ok.png"))); // NOI18N
        jbEditar.setMnemonic('A');
        jbEditar.setText(resourceMap.getString("jbEditar.text")); // NOI18N
        jbEditar.setName("jbEditar"); // NOI18N
        jbEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbEditarActionPerformed(evt);
            }
        });
        jbEditar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jbEditarKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel18)
                        .addGap(13, 13, 13)
                        .addComponent(jtfRuc, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jtfEmpresa, javax.swing.GroupLayout.PREFERRED_SIZE, 347, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(23, 23, 23)
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 262, Short.MAX_VALUE)
                        .addComponent(jbEditar)
                        .addGap(18, 18, 18)
                        .addComponent(jbCancelar)))
                .addContainerGap())
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(16, 16, 16)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 626, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(jLabel18)
                    .addComponent(jtfRuc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jtfEmpresa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 342, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbCancelar)
                    .addComponent(jButton1)
                    .addComponent(jbEditar))
                .addContainerGap())
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(48, 48, 48)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 311, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(52, Short.MAX_VALUE)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jtfEmpresaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtfEmpresaActionPerformed

        this.buscarEmpresa();
}//GEN-LAST:event_jtfEmpresaActionPerformed

    private void jtfEmpresaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfEmpresaKeyPressed
        if (this.jtfRuc.getText().trim().length() > 0)
            this.jtfRuc.setText("");
}//GEN-LAST:event_jtfEmpresaKeyPressed

    private void jtfRucActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtfRucActionPerformed
         if (this.jtfRuc.getText().trim().length() < 1)
            this.jtfRuc.requestFocus();
        else
            this.buscarEmpresa();
}//GEN-LAST:event_jtfRucActionPerformed

    private void jtfRucKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfRucKeyPressed
      
}//GEN-LAST:event_jtfRucKeyPressed

    private void jbCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbCancelarActionPerformed

        this.dispose();
}//GEN-LAST:event_jbCancelarActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        try {
             this.empresas_temp.clear();
            this.empresas = GestionPedidosDelegate.getInstance().obtenerEmpresas();
            this.actualizaTablaEmpresas(this.empresas);
        } catch (Exception ex) {
            Logger.getLogger(jdVerUsuarios.class.getName()).log(Level.SEVERE, null, ex);
        }
}//GEN-LAST:event_jButton1ActionPerformed

    private void jbEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbEditarActionPerformed
        EmpresaTO empresa;
        int filaElegida = this.jtEmpresas.getSelectedRow();

        if (filaElegida < 0) {
            Utiles_MensajesDialogo.mensajeError("Debe elegir una Empresa!");
            this.jtEmpresas.requestFocus();
            return;
        } else{
            if(this.empresas_temp.isEmpty())
                empresa  = (EmpresaTO)this.empresas.get(filaElegida);
            else
                 empresa  = (EmpresaTO)this.empresas_temp.get(filaElegida);
            
           jdRegistrarEmpresa  jd =  new jdRegistrarEmpresa(null,true,true);
            try {
                jd.setEmpresaEdit(empresa);
            } catch (Exception ex) {
                Logger.getLogger(jdOperacionesEmpresa.class.getName()).log(Level.SEVERE, null, ex);
            }
           jd.setLocationRelativeTo(null);
           jd.setVisible(true);
           
        }
}//GEN-LAST:event_jbEditarActionPerformed

    private void jbEditarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jbEditarKeyPressed
        
}//GEN-LAST:event_jbEditarKeyPressed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                jdOperacionesEmpresa dialog = new jdOperacionesEmpresa(new javax.swing.JFrame(), true,false);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbCancelar;
    private javax.swing.JButton jbEditar;
    private javax.swing.JTable jtEmpresas;
    private javax.swing.JTextField jtfEmpresa;
    private javax.swing.JTextField jtfRuc;
    // End of variables declaration//GEN-END:variables

}
